/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.engine.cmd.task;

import cn.easyplatform.contexts.WorkflowContext;
import cn.easyplatform.dos.LogDo;
import cn.easyplatform.interceptor.AbstractCommand;
import cn.easyplatform.interceptor.CommandContext;
import cn.easyplatform.messages.request.SimpleRequestMessage;
import cn.easyplatform.messages.response.SimpleResponseMessage;
import cn.easyplatform.type.Constants;
import cn.easyplatform.type.IResponseMessage;
import cn.easyplatform.util.MessageUtils;
import cn.easyplatform.util.RuntimeUtils;


/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class CloseCmd extends AbstractCommand<SimpleRequestMessage> {

    /**
     * @param req
     */
    public CloseCmd(SimpleRequestMessage req) {
        super(req);
    }

    @Override
    public IResponseMessage<?> execute(CommandContext cc) {
        WorkflowContext ctx = cc.getWorkflowContext();
        if (ctx != null) {
            Object src = ctx.getParameter("826");
            String code = "0000";
            if (src != null) {
                ctx.getRecord().setParameter("808", Constants.ON_CLOSE);
                code = RuntimeUtils.eval(cc, src, ctx.getRecord());
            }
            if (cc.getUser().getLogLevel() >= LogDo.LEVEL_TASK)
                RuntimeUtils.log(cc, LogDo.TYPE_TASK, "close",
                        ctx.getParameterAsString("801"));
            if (code.equals("0000"))
                cc.removeWorkflowContext();
            else
                return MessageUtils.byErrorCode(cc, ctx.getRecord(), ctx.getId(),
                        code);
        }
        return new SimpleResponseMessage();
    }

    @Override
    public String getName() {
        return "task.Close";
    }
}
